<script setup lang="ts">
declare global {
  interface Window {
    _AMapSecurityConfig: {
      securityJsCode: string;
    };
  }
}

import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue';
import { useRouter } from 'vue-router';
import { PhImage, PhLockKey, PhGlobe } from '@phosphor-icons/vue';
import ArticleMenu from '@/components/article-menu.vue';
import ArticleTopBg from '@/components/article-top-bg.vue';
import LayoutFooter from '@/components/layout-footer.vue';
import AMapLoader from '@amap/amap-jsapi-loader';

// 配置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: '7233cf42dd6ffded20c641a7d7c64ad7'
};

interface Location {
  name: string;
  latitude: number;
  longitude: number;
}

interface Album {
  id: string;
  title: string;
  description: string;
  coverUrl: string;
  photoCount: number;
  createTime: string;
  isPrivate: boolean;
  location?: Location;
}

const router = useRouter();
const albums = ref<Album[]>([]);
const loading = ref(true);
const viewMode = ref<'grid' | 'map'>('grid');
const map = ref<any>(null);
const selectedAlbum = ref<Album | null>(null);

// 计算位置总数
const locationCount = computed(() => {
  const uniqueLocations = new Set();
  albums.value.forEach(album => {
    if (album.location) {
      uniqueLocations.add(`${album.location.latitude},${album.location.longitude}`);
    }
  });
  return uniqueLocations.size;
});

const groupAlbumsByLocation = (albums: Album[]) => {
  const groups = new Map<string, Album[]>();

  albums.forEach(album => {
    if (album.location) {
      const key = `${album.location.latitude},${album.location.longitude}`;
      if (!groups.has(key)) {
        groups.set(key, []);
      }
      groups.get(key)!.push(album);
    }
  });

  return groups;
};
// 初始化地图
const initMap = async () => {
  try {
    await nextTick();

    const container = document.getElementById('map-container');
    if (!container) {
      console.error('地图容器不存在');
      return;
    }

    const AMap = await AMapLoader.load({
      key: '459e59abdcc69ab9aaa80167f6f9cf78',
      version: '2.0',
      plugins: ['AMap.Marker', 'AMap.InfoWindow', 'AMap.DistrictSearch', 'AMap.Scale', 'AMap.ToolBar']
    });

    map.value = new AMap.Map('map-container', {
      viewMode: '2D',
      zoom: 11,
      center: [116.397428, 39.90923],
      mapStyle: 'amap://styles/normal',
      features: ['bg', 'road', 'building', 'point'],
      expandZoomRange: true,
      zooms: [3, 20],
    });

    // 添加比例尺控件
    map.value.addControl(new AMap.Scale({
      position: 'LB' // 左下角
    }));

    // 添加工具条控件
    map.value.addControl(new AMap.ToolBar({
      position: 'RB', // 右下角
      offset: [20, 20], // 偏移量
      ruler: true, // 显示标尺
      locate: true // 显示定位按钮
    }));

    // 按位置分组相册
    const albumGroups = groupAlbumsByLocation(albums.value);

    albumGroups.forEach((groupAlbums, locationKey) => {
      const [lat, lng] = locationKey.split(',').map(Number);
      const location = groupAlbums[0].location!;

      const marker = new AMap.Marker({
        position: [lng, lat],
        offset: new AMap.Pixel(-13, -30),
        cursor: 'pointer',
        content: `
          <div style="
            position: relative;
            width: 25px;
            height: 34px;
          ">
            <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png"
                 style="width: 25px; height: 34px;"/>
            ${groupAlbums.length > 1 ? `
              <div style="
                position: absolute;
                top: -5px;
                right: -5px;
                background: #ff4d4f;
                color: white;
                border-radius: 50%;
                width: 18px;
                height: 18px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 12px;
                font-weight: bold;
                box-shadow: 0 2px 4px rgba(0,0,0,0.2);
              ">${groupAlbums.length}</div>
            ` : ''}
          </div>
        `
      });

      // 创建信息窗体
      const infoWindow = new AMap.InfoWindow({
        isCustom: true,
        content: createMultiAlbumContent(groupAlbums, location.name, router),
        offset: new AMap.Pixel(0, -35),
        closeWhenClickMap: false,
        autoMove: true,
        anchor: 'bottom-center'
      });

      let closeTimer: NodeJS.Timeout | null = null;

      // 鼠标移入标记点显示信息窗体
      marker.on('mouseover', () => {
        if (closeTimer) {
          clearTimeout(closeTimer);
          closeTimer = null;
        }
        infoWindow.open(map.value, marker.getPosition());
      });

      // 鼠标移出标记点
      marker.on('mouseout', () => {
        closeTimer = setTimeout(() => {
          infoWindow.close();
        }, 300);
      });

      // 点击标记点也显示信息窗体
      marker.on('click', () => {
        if (closeTimer) {
          clearTimeout(closeTimer);
          closeTimer = null;
        }
        infoWindow.open(map.value, marker.getPosition());
      });

      map.value.add(marker);

      // 监听信息窗体的鼠标事件
      infoWindow.on('mouseover', () => {
        if (closeTimer) {
          clearTimeout(closeTimer);
          closeTimer = null;
        }
      });

      infoWindow.on('mouseout', () => {
        closeTimer = setTimeout(() => {
          infoWindow.close();
        }, 300);
      });
    });

    // 自适应缩放级别，设置最小级别为11
    map.value.setFitView(null, false, [60, 60, 60, 60], 11);

    // 添加地图缩放事件监听
    map.value.on('zoomend', () => {
      const zoom = map.value.getZoom();
      console.log('当前缩放级别:', zoom);
    });

    // 添加地图移动结束事件监听
    map.value.on('moveend', () => {
      const center = map.value.getCenter();
      console.log('地图中心点:', center.toString());
    });

    // 添加地图加载完成事件监听
    map.value.on('complete', () => {
      console.log('地图加载完成');
    });

  } catch (error) {
    console.error('地图初始化失败:', error);
  }
};

// 修改视图切换处理函数
const handleTransitionComplete = () => {
  if (viewMode.value === 'map') {
    initMap();
  }
};

// 创建信息窗体内容
const createMultiAlbumContent = (albums: Album[], locationName: string, router: any) => {
  // 创建唯一的函数名
  const functionName = `handleAlbumClick_${Date.now()}`;

  // 在全局注册点击处理函数
  (window as any)[functionName] = (albumId: string, isPrivate: boolean) => {
    if (isPrivate) {
      router.push(`/albums/verify/${albumId}`);
    } else {
      router.push(`/albums/${albumId}`);
    }
  };

  return `
    <div class="map-info-window" style="
      width: 240px;
      background: white;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    ">
      <div style="
        padding: 8px;
        border-bottom: 1px solid #f0f0f0;
        font-size: 12px;
        color: #666;
        display: flex;
        align-items: center;
      ">
        <svg viewBox="0 0 24 24" width="14" height="14" style="margin-right: 4px;" fill="currentColor">
          <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
        </svg>
        <span>${locationName}</span>
        <span style="margin-left: 8px; color: #999;">${albums.length} 个相册</span>
      </div>
      <div style="
        max-height: 320px;
        overflow-y: auto;
        padding: 4px;
      ">
        ${albums.map(album => `
          <div onclick="${functionName}('${album.id}', ${album.isPrivate})"
               style="
                 padding: 8px;
                 display: flex;
                 gap: 12px;
                 cursor: pointer;
                 border-radius: 6px;
                 transition: all 0.3s ease;
                 margin-bottom: 4px;
               "
               onmouseover="this.style.backgroundColor='#f5f5f5'"
               onmouseout="this.style.backgroundColor='transparent'"
          >
            <div style="
              width: 70px;
              height: 70px;
              flex-shrink: 0;
              overflow: hidden;
              border-radius: 6px;
              position: relative;
            ">
              <img src="${album.coverUrl}" style="
                width: 100%;
                height: 100%;
                object-fit: cover;
                transition: transform 0.3s ease;
              " onmouseover="this.style.transform='scale(1.1)'"
                 onmouseout="this.style.transform='scale(1)'">
              ${album.isPrivate ? `
                <div style="
                  position: absolute;
                  top: 4px;
                  right: 4px;
                  padding: 2px 6px;
                  background: rgba(0,0,0,0.6);
                  color: white;
                  border-radius: 4px;
                  font-size: 10px;
                  display: flex;
                  align-items: center;
                  gap: 2px;
                ">
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 17a2 2 0 100-4 2 2 0 000 4z"/>
                    <path fill-rule="evenodd" d="M18 8a6 6 0 00-12 0v3H4v10h16V11h-2V8zm-6-4a4 4 0 014 4v3H8V8a4 4 0 014-4z"/>
                  </svg>
                  私密
                </div>
              ` : ''}
            </div>
            <div style="
              flex-grow: 1;
              min-width: 0;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
            ">
              <div>
                <h4 style="
                  margin: 0 0 4px 0;
                  font-size: 14px;
                  color: #1e293b;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                  overflow: hidden;
                  line-height: 1.3;
                ">${album.title}</h4>
                <p style="
                  margin: 0;
                  font-size: 12px;
                  color: #64748b;
                  display: -webkit-box;
                  -webkit-line-clamp: 1;
                  -webkit-box-orient: vertical;
                  overflow: hidden;
                ">${album.description || ''}</p>
              </div>
              <div style="
                margin-top: 4px;
                font-size: 11px;
                color: #94a3b8;
                display: flex;
                justify-content: space-between;
                align-items: center;
              ">
                <div style="display: flex; align-items: center; gap: 8px;">
                  <span>
                    <svg viewBox="0 0 24 24" width="12" height="12" style="
                      margin-right: 2px;
                      vertical-align: -1px;
                    " fill="currentColor">
                      <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/>
                    </svg>
                    ${album.photoCount}
                  </span>
                  <span>
                    <svg viewBox="0 0 24 24" width="12" height="12" style="
                      margin-right: 2px;
                      vertical-align: -1px;
                    " fill="currentColor">
                      <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/>
                    </svg>
                    ${album.createTime}
                  </span>
                </div>
              </div>
            </div>
          </div>
        `).join('')}
      </div>
    </div>
  `;
};

// 切换视图模式
const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'grid' ? 'map' : 'grid';
};

// 点击相册
const handleAlbumClick = (album: Album) => {
  if (album.isPrivate) {
    router.push(`/albums/verify/${album.id}`);
  } else {
    router.push(`/albums/${album.id}`);
  }
};

// 获取相册列表
const fetchAlbums = async () => {
  try {
    loading.value = true;
    // 模拟数据
    albums.value = [
      {
        id: '1',
        title: '北京之旅',
        description: '在北京的美好时光',
        coverUrl: 'https://image.starmist.net/blog/article-cover/0d8ad4f9-1723-44fe-a085-8da78345a731.webp',
        photoCount: 24,
        createTime: '2024-01-15',
        isPrivate: true,
        location: {
          name: '北京',
          latitude: 39.90923,
          longitude: 116.397428
        }
      },
      {
        id: '2',
        title: '上海行记',
        description: '魔都的繁华与温情',
        coverUrl: 'https://image.starmist.net/blog/article-cover/0228b46a-3cdc-4787-a1ed-2ae051fd63b5.webp',
        photoCount: 36,
        createTime: '2024-02-20',
        isPrivate: false,
        location: {
          name: '上海',
          latitude: 31.230416,
          longitude: 121.473701
        }
      },
      {
        id: '3',
        title: '济南印象',
        description: '岭南文化的魅力',
        coverUrl: 'https://image.starmist.net/blog/background/fd173df3-9b60-41b6-9cb5-570ac93893f9.jpg',
        photoCount: 42,
        createTime: '2024-03-10',
        isPrivate: false,
        location: {
          name: '济南',
          latitude: 36.40000,
          longitude: 116.561501
        }
      }
    ];
  } catch (error) {
    console.error('获取相册列表失败:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchAlbums();
});

onUnmounted(() => {
  if (map.value) {
    map.value.destroy();
    map.value = null;
  }
});
</script>

<template>
  <div class="layout-container">
    <ArticleMenu />
    <ArticleTopBg
      height="400px"
      title="相册集"
      :subtitles="'记录生活中的每个精彩瞬间'"
    />

    <div class="container">
      <!-- 更新的统计和控制区域 -->
      <div class="album-stats">
        <div class="stat-card">
          <div class="stat-icon" style="background-color: #6366f1;">
            <PhImage :size="20" weight="fill" />
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ albums.length }}</div>
            <div class="stat-label">相册总数</div>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon" style="background-color: #38bdf8;">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M21 19V5C21 3.9 20.1 3 19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19ZM8.5 13.5L11 16.51L14.5 12L19 18H5L8.5 13.5Z" fill="currentColor"/>
            </svg>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ albums.reduce((sum, album) => sum + album.photoCount, 0) }}</div>
            <div class="stat-label">照片总数</div>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon" style="background-color: #f43f5e;">
            <PhLockKey :size="20" weight="fill" />
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ albums.filter(album => album.isPrivate).length }}</div>
            <div class="stat-label">私密相册</div>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon" style="background-color: #10b981;">
            <PhGlobe :size="20" weight="fill" />
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ locationCount }}</div>
            <div class="stat-label">覆盖地点</div>
          </div>
        </div>

        <div class="view-buttons">
          <button
            class="view-btn"
            :class="{ active: viewMode === 'grid' }"
            @click="viewMode = 'grid'"
          >
            <PhImage :size="18" />
            <span>网格视图</span>
          </button>
          <button
            class="view-btn"
            :class="{ active: viewMode === 'map' }"
            @click="toggleViewMode"
          >
            <PhGlobe :size="18" />
            <span>地图视图</span>
          </button>
        </div>
      </div>

      <Transition name="fade" mode="out-in" @after-leave="handleTransitionComplete">
        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" key="grid" class="view-container">
          <div v-if="loading" class="albums-grid">
            <div v-for="i in 6" :key="i" class="album-card skeleton">
              <div class="cover-skeleton"></div>
              <div class="info-skeleton">
                <div class="title-skeleton"></div>
                <div class="desc-skeleton"></div>
              </div>
            </div>
          </div>
          <TransitionGroup
            v-else
            name="album-list"
            tag="div"
            class="albums-grid"
            appear
          >
            <div
              v-for="album in albums"
              :key="album.id"
              class="album-card"
              @click="handleAlbumClick(album)"
            >
              <div class="album-cover">
                <img :src="album.coverUrl" :alt="album.title">
                <div v-if="album.isPrivate" class="private-badge">
                  <PhLockKey :size="16" />
                  私密
                </div>
              </div>
              <div class="album-info">
                <h3 class="album-title">{{ album.title }}</h3>
                <p class="album-description">{{ album.description }}</p>
                <div class="album-meta">
                  <span>{{ album.photoCount }} 张照片</span>
                  <span>{{ album.createTime }}</span>
                </div>
              </div>
            </div>
          </TransitionGroup>
        </div>

        <!-- 地图视图 -->
        <div v-else key="map" class="map-view">
          <div id="map-container"></div>
        </div>
      </Transition>
    </div>

    <LayoutFooter />
  </div>
</template>

<style scoped lang="less">
.container {
  max-width: 1161px;
  margin: 0 auto;
  padding: 80px 20px 40px;
}

.view-container {
  width: 100%;
}

// 新的统计和控制区域样式
.album-stats {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  .stat-card {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 140px;

    .stat-icon {
      width: 42px;
      height: 42px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      margin-right: 12px;
    }

    .stat-info {
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #1e293b;
        line-height: 1.2;
      }

      .stat-label {
        font-size: 13px;
        color: #64748b;
      }
    }
  }

  .view-buttons {
    display: flex;
    gap: 10px;
    margin-left: auto;

    .view-btn {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 8px 14px;
      border-radius: 8px;
      border: 1px solid #e2e8f0;
      background: white;
      color: #64748b;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        background: #f8fafc;
      }

      &.active {
        background: #1e293b;
        color: white;
        border-color: #1e293b;
      }
    }
  }
}

.albums-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  position: relative;
}

.album-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }

  .album-cover {
    position: relative;
    aspect-ratio: 16/9;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .private-badge {
      position: absolute;
      top: 12px;
      right: 12px;
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 6px 12px;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      border-radius: 6px;
      font-size: 12px;
    }
  }

  .album-info {
    padding: 20px;

    .album-title {
      font-size: 18px;
      font-weight: 600;
      color: #1e293b;
      margin-bottom: 8px;
    }

    .album-description {
      color: #64748b;
      font-size: 14px;
      margin-bottom: 16px;
      line-height: 1.5;
    }

    .album-meta {
      display: flex;
      justify-content: space-between;
      color: #94a3b8;
      font-size: 12px;
    }
  }
}

.map-view {
  width: 100%;
  height: 600px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  background: #f5f5f5;
  animation: fadeIn 0.5s ease;

  #map-container {
    width: 100%;
    height: 100%;
  }
}

// 视图切换动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 相册列表动画
.album-list-move,
.album-list-enter-active,
.album-list-leave-active {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.album-list-enter-from {
  opacity: 0;
  transform: scale(0.9) translateY(30px);
}

.album-list-leave-to {
  opacity: 0;
  transform: scale(0.9) translateY(-30px);
}

.album-list-leave-active {
  position: absolute;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 骨架屏
.skeleton {
  pointer-events: none;

  .cover-skeleton {
    aspect-ratio: 16/9;
    background: linear-gradient(
      90deg,
      #f0f0f0 25%,
      #e0e0e0 50%,
      #f0f0f0 75%
    );
    background-size: 200% 100%;
    animation: shimmer 1.5s infinite;
  }

  .info-skeleton {
    padding: 20px;

    .title-skeleton {
      height: 24px;
      width: 70%;
      background-color: #f0f0f0;
      border-radius: 4px;
      margin-bottom: 12px;
    }

    .desc-skeleton {
      height: 16px;
      width: 90%;
      background-color: #f0f0f0;
      border-radius: 4px;
    }
  }
}

@keyframes shimmer {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

// 响应式设计
@media (max-width: 992px) {
  .album-stats {
    flex-wrap: wrap;
    gap: 16px;

    .stat-card {
      min-width: calc(50% - 8px);
      flex: 0 0 calc(50% - 8px);
    }

    .view-buttons {
      width: 100%;
      margin-left: 0;
      margin-top: 8px;
      justify-content: flex-end;
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 60px 12px 24px;
  }

  .album-stats {
    padding: 16px;

    .stat-card {
      min-width: calc(50% - 8px);

      .stat-icon {
        width: 36px;
        height: 36px;
      }

      .stat-info {
        .stat-value {
          font-size: 20px;
        }

        .stat-label {
          font-size: 12px;
        }
      }
    }

    .view-buttons {
      .view-btn {
        flex: 1;
        justify-content: center;

        span {
          display: none;
        }
      }
    }
  }

  .map-view {
    height: 400px;
  }

  .albums-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }
}

@media (max-width: 576px) {
  .album-stats {
    .stat-card {
      min-width: 100%;
      flex: 0 0 100%;
    }
  }

  .albums-grid {
    grid-template-columns: 1fr;
  }
}
</style>
